#include "PptpSocket.h"

PptpSocket::PptpSocket(QObject *parent)
    : QObject{parent}
{
    socket = new QTcpSocket();
    // qDebug() << "new PptpSocket";
    messageLength = -1;
    connect(socket, &QTcpSocket::readyRead, this, &PptpSocket::onReadyRead);
    connect(socket, &QTcpSocket::disconnected, this, [this]
            {
        // qDebug() << "QTcpDisconnect";
        emit pptpDisconnect(); });
}

PptpSocket::PptpSocket(QTcpSocket *socket, QObject *parent)
    : QObject{parent}
{
    this->socket = socket;
    messageLength = -1;
    // qDebug() << "new PptpSocket by socket";
    connect(socket, &QTcpSocket::readyRead, this, &PptpSocket::onReadyRead);
    connect(socket, &QTcpSocket::disconnected, this, [this]
            {
                // qDebug() << "QTcpDisconnect";
                emit pptpDisconnect(); });
}

PptpSocket::~PptpSocket()
{
    // qDebug() << "~PptpSocket";
    socket->disconnectFromHost();
    socket->deleteLater();
}

void PptpSocket::connectToHost(QString ip, QString port)
{
    connect(socket, &QTcpSocket::connected, this, [this]
            { emit pptpConnect(); });
    socket->connectToHost(QHostAddress(ip), port.toInt());
}

void PptpSocket::pptpWrite(QByteArray writeMessage)
{
    // qDebug() << "Send Message: " << writeMessage;
    // writeMessage = xorEncryptDecrypt(writeMessage, "PiliPiliTransferProtocol");
    QByteArray length = QByteArray::number(writeMessage.size()) + "\r\n";
    QByteArray fullMessage = length + writeMessage;
    qint64 totalBytes = fullMessage.size();
    qint64 bytesWritten = 0;

    while (bytesWritten < totalBytes)
    {
        qint64 bytes = socket->write(fullMessage.mid(bytesWritten));
        if (bytes <= 0)
        {
            // 处理错误
            qDebug() << "Error writing to socket: " << socket->errorString();
            return;
        }
        bytesWritten += bytes;

        // 等待数据被实际发送
        if (!socket->waitForBytesWritten(60000))
        {
            // 处理超时或其他错误
            qDebug() << "Error waiting for bytes to be written: " << socket->errorString();
            return;
        }
    }

    // qDebug() << "All data sent successfully.";
}

void PptpSocket::onReadyRead()
{
    // qDebug() << "onReadyRead";
    // QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    buffer.append(socket->readAll());
    // qDebug() << "Buffer: " << buffer;
    if (messageLength == -1)
    {
        int index = buffer.indexOf("\r\n");
        if (index == -1)
        {
            return;
        }
        QByteArray line = buffer.left(index).trimmed();
        buffer.remove(0, index + 2);
        messageLength = line.toInt();
    }
    if (buffer.size() == messageLength)
    {
        // buffer = xorEncryptDecrypt(buffer, "PiliPiliTransferProtocol");
        // qDebug() << "Receive Buffer: " << buffer;
        // qDebug() << "readCompletedSignal";
        emit readCompletedSignal(buffer);
    }
}

// QByteArray PptpSocket::xorEncryptDecrypt(const QByteArray &data, const QByteArray &key)
// {
//     QByteArray result;
//     for (int i = 0; i < data.size(); ++i)
//     {
//         result.append(data[i] ^ key[i % key.size()]);
//     }
//     return result;
// }
